package safeCommitter.core.launcher.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.eclipse.jdt.launching.SocketUtil;

/**
 * This class will be listening on a new Thread on a producer-consumer schema
 * for the test results. The test results are sent on a socket structure.
 * 
 * @see
 * 
 * 
 * @author Luiz Henrique Rolim
 */
public abstract class SCSocketReader implements Runnable {

	private BufferedReader reader;

	private final Integer port;

	protected Boolean jobDone = Boolean.FALSE;

	public SCSocketReader() {
		this.port = SocketUtil.findFreePort();
	}

	public void run() {
		connect();
	}

	public void connect() {
		try {
			ServerSocket server = new ServerSocket(port);
			try {
				Socket socket = server.accept();
				try {
					readMessage(socket);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					socket.close();
				}
			} finally {
				server.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void readMessage(final Socket socket) throws IOException,
			InterruptedException {
		reader = new BufferedReader(new InputStreamReader(socket
				.getInputStream()));
		try {
			String line = null;
			while ((line = reader.readLine()) != null) {
				parseMessage(line);
				Thread.sleep(150);
			}
		} finally {
			reader.close();
		}
	}

	/**
	 * Parses a message that will be sent through a socket connection.
	 * 
	 * 
	 * @param line
	 */
	protected abstract void parseMessage(final String line);

	public abstract Boolean getTestsPassing();

	public Integer getPort() {
		return port;
	}

	public Boolean getJobDone() {
		return jobDone;
	}

}
